// pages/products/products.js
Page({
  data: {
    // 搜索和筛选
    searchKeyword: '',
    selectedCategory: '',
    showFilter: false,
    filterMinPrice: '',
    filterMaxPrice: '',

    // 分页和加载状态
    loading: false,
    loadingMore: false,
    hasMore: true,
    page: 1,
    pageSize: 20,
    total: 0,

    // 数据
    products: [],
    categories: [],

    // AI处理状态
    aiProcessing: false,
    aiProgress: 0
  },

  onLoad() {
    console.log('📱 全部商品页面加载');

    // 检查登录状态
    const app = getApp();
    if (!app.checkPageAuth('pages/products/products')) {
      return;
    }

    this.initializeData();
  },

  onShow() {
    console.log('📱 全部商品页面显示');
  },

  onPullDownRefresh() {
    console.log('🔄 下拉刷新商品列表');
    this.refreshProducts();
  },

  onReachBottom() {
    console.log('📄 触底加载更多商品');
    this.loadMoreProducts();
  },

  // 初始化数据
  initializeData() {
    // 同时加载分类和商品
    Promise.all([
      this.loadCategories(),
      this.loadProducts()
    ]).catch(error => {
      console.error('❌ 初始化数据失败:', error);
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    });
  },

  // 加载商品分类
  async loadCategories() {
    const app = getApp();
    const token = app.globalData.token;

    if (!token) {
      console.log('⚠️ 用户未登录，无法加载分类');
      return;
    }

    try {
      console.log('🏷️ 加载商品分类...');

      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/products/categories`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: resolve,
          fail: reject
        });
      });

      console.log('📥 分类API响应:', response);

      if (response.statusCode === 200 && response.data.code === 1) {
        this.setData({
          categories: response.data.data || []
        });
        console.log('✅ 分类加载成功:', response.data.data.length, '个分类');
      } else {
        throw new Error(response.data.msg || '获取分类失败');
      }
    } catch (error) {
      console.error('❌ 加载分类失败:', error);
      // 分类加载失败不影响商品加载，只是没有分类筛选功能
    }
  },

  // 加载商品列表
  async loadProducts(isLoadMore = false) {
    const app = getApp();
    const token = app.globalData.token;

    if (!token) {
      console.log('⚠️ 用户未登录，无法加载商品');
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 设置加载状态
    if (isLoadMore) {
      this.setData({ loadingMore: true });
    } else {
      this.setData({ loading: true });
    }

    try {
      console.log('🛍️ 加载商品列表...', {
        page: this.data.page,
        pageSize: this.data.pageSize,
        keyword: this.data.searchKeyword,
        category: this.data.selectedCategory,
        minPrice: this.data.filterMinPrice,
        maxPrice: this.data.filterMaxPrice
      });

      // 构建查询参数
      const params = {
        page: this.data.page,
        pageSize: this.data.pageSize
      };

      if (this.data.searchKeyword) {
        params.keyword = this.data.searchKeyword;
      }

      if (this.data.selectedCategory) {
        // 这里需要根据分类名称映射到cateId，暂时跳过
        // params.cateId = this.getCategoryId(this.data.selectedCategory);
      }

      if (this.data.filterMinPrice) {
        params.minPrice = this.data.filterMinPrice;
      }

      if (this.data.filterMaxPrice) {
        params.maxPrice = this.data.filterMaxPrice;
      }

      // 构建URL
      const queryString = Object.keys(params)
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&');

      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/products?${queryString}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: resolve,
          fail: reject
        });
      });

      console.log('📥 商品API响应:', response);

      if (response.statusCode === 200 && response.data.code === 1) {
        const { total, rows } = response.data.data;

        // 处理商品数据，添加服装类型检测
        const processedProducts = rows.map(product => ({
          ...product,
          clothesType: this.detectClothesType(product.productName) || product.clothesType || 'Upper-body',
          tryOnLoading: false
        }));

        // 更新商品列表
        if (isLoadMore) {
          this.setData({
            products: [...this.data.products, ...processedProducts],
            total: total,
            hasMore: this.data.products.length + processedProducts.length < total
          });
        } else {
          this.setData({
            products: processedProducts,
            total: total,
            hasMore: processedProducts.length < total
          });
        }

        console.log('✅ 商品加载成功:', processedProducts.length, '件商品');
      } else {
        throw new Error(response.data.msg || '获取商品失败');
      }
    } catch (error) {
      console.error('❌ 加载商品失败:', error);
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    } finally {
      // 清除加载状态
      this.setData({
        loading: false,
        loadingMore: false
      });

      // 停止下拉刷新
      wx.stopPullDownRefresh && wx.stopPullDownRefresh();
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 执行搜索
  onSearchConfirm() {
    console.log('🔍 执行搜索:', this.data.searchKeyword);
    this.refreshProducts();
  },

  // 选择分类
  selectCategory(e) {
    const category = e.currentTarget.dataset.category;
    console.log('🏷️ 选择分类:', category);

    this.setData({
      selectedCategory: category
    });

    // 如果是本地定义的分类，使用本地筛选
    const localCategories = ['连衣裙', 'T恤', '牛仔裤', '衬衫', '外套', '休闲'];
    if (category && localCategories.includes(category)) {
      this.filterProductsByLocalCategory(category);
    } else {
      this.refreshProducts();
    }
  },

  // 根据本地分类筛选商品
  filterProductsByLocalCategory(category) {
    console.log('🔍 本地筛选分类:', category);
    
    const allProducts = this.data.products;
    let filteredProducts = allProducts;

    if (category) {
      // 定义分类关键词映射
      const categoryKeywords = {
        '连衣裙': ['连衣裙', '裙子', '长裙', '短裙', 'dress'],
        'T恤': ['T恤', 't恤', 'T-shirt', 'tee', '短袖', '上衣'],
        '牛仔裤': ['牛仔裤', '牛仔', 'jeans', '长裤'],
        '衬衫': ['衬衫', '衬衣', 'shirt', '白衬衫'],
        '外套': ['外套', '夹克', '风衣', 'jacket', 'coat'],
        '休闲': ['休闲', '运动', 'casual', '舒适']
      };

      const keywords = categoryKeywords[category] || [];
      
      filteredProducts = allProducts.filter(product => {
        const productName = (product.productName || '').toLowerCase();
        return keywords.some(keyword => 
          productName.includes(keyword.toLowerCase())
        );
      });

      console.log(`📦 ${category}分类筛选结果: ${filteredProducts.length}/${allProducts.length}`);
    }

    // 这里不改变原始products数组，只是重新渲染
    // 如果需要分页等功能，可能需要更复杂的实现
  },

  // 刷新商品列表
  refreshProducts() {
    this.setData({
      page: 1,
      hasMore: true,
      products: []
    });
    this.loadProducts();
  },

  // 加载更多商品
  loadMoreProducts() {
    if (this.data.loadingMore || !this.data.hasMore) {
      return;
    }

    this.setData({
      page: this.data.page + 1
    });

    this.loadProducts(true);
  },

  // 显示筛选弹窗
  showFilterModal() {
    this.setData({
      showFilter: true
    });
  },

  // 隐藏筛选弹窗
  hideFilterModal() {
    this.setData({
      showFilter: false
    });
  },

  // 最低价格输入
  onMinPriceInput(e) {
    this.setData({
      filterMinPrice: e.detail.value
    });
  },

  // 最高价格输入
  onMaxPriceInput(e) {
    this.setData({
      filterMaxPrice: e.detail.value
    });
  },

  // 重置筛选
  resetFilter() {
    this.setData({
      filterMinPrice: '',
      filterMaxPrice: ''
    });
  },

  // 应用筛选
  applyFilter() {
    console.log('🔽 应用筛选:', {
      minPrice: this.data.filterMinPrice,
      maxPrice: this.data.filterMaxPrice
    });

    this.hideFilterModal();
    this.refreshProducts();
  },

  // 检测服装类型（复用首页的逻辑）
  detectClothesType(productName) {
    if (!productName) {
      return 'Upper-body';
    }

    console.log('🔍 检测服装类型:', productName);

    // 下装关键词检测
    const lowerBodyKeywords = [
      '裤', '短裤', '长裤', '牛仔裤', '休闲裤', '运动裤',
      '西裤', '打底裤', '九分裤', '七分裤', '五分裤',
      'pants', 'jeans', 'trouser', 'legging'
    ];

    // 连衣裙关键词检测
    const dressKeywords = [
      '连衣裙', '长裙', '短裙', '半身裙', '裙子', '裙',
      'dress', 'skirt'
    ];

    // 检测下装
    for (let keyword of lowerBodyKeywords) {
      if (productName.includes(keyword)) {
        console.log('✅ 检测为下装，匹配关键词:', keyword);
        return 'Lower-body';
      }
    }

    // 检测连衣裙
    for (let keyword of dressKeywords) {
      if (productName.includes(keyword)) {
        console.log('✅ 检测为连衣裙，匹配关键词:', keyword);
        return 'Dress';
      }
    }

    // 默认为上装
    console.log('⚠️ 未匹配到特定关键词，默认为上装');
    return 'Upper-body';
  },

  // 更新商品状态
  updateProductState(productId, newState) {
    const products = this.data.products.map(product => {
      if (product.productId === productId) {
        return { ...product, ...newState };
      }
      return product;
    });

    this.setData({ products });
  },

  // 试穿商品（复用首页的逻辑）
  async tryOnProduct(e) {
    e.stopPropagation();

    const item = e.currentTarget.dataset.product;
    console.log('👗 开始试穿商品:', item);

    // 检查算力余额（这里需要获取最新的用户信息）
    const app = getApp();
    const userInfo = app.globalData.userInfo;

    if (!userInfo || !userInfo.tokenBalance || userInfo.tokenBalance < 1) {
      wx.showModal({
        title: '算力不足',
        content: '您的算力余额不足，请联系管理员充值',
        showCancel: false
      });
      return;
    }

    // 设置试穿加载状态
    this.updateProductState(item.productId, { tryOnLoading: true });

    // 显示AI处理动画
    this.setData({
      aiProcessing: true,
      aiProgress: 0
    });

    // 模拟进度条
    const progressTimer = setInterval(() => {
      if (this.data.aiProgress < 90) {
        this.setData({
          aiProgress: this.data.aiProgress + Math.random() * 10
        });
      }
    }, 500);

    try {
      // 获取模特图片（从首页或默认图片）
      const modelImage = app.globalData.modelImage ||
                        'https://ceshi-1337249743.cos.ap-beijing.myqcloud.com/uploads/avatar/2025/08/03/avatar_1754230169473_a3a3222f.png';
      const clothingImage = item.productImage;
      const token = app.globalData.token;

      // 调用AI换装API
      const clothesType = this.detectClothesType(item.productName) || item.clothesType || 'Upper-body';
      console.log('🔍 使用服装类型:', clothesType);

      const result = await this.callTryOnAPI(modelImage, clothingImage, token, clothesType);

      // 清除进度条定时器
      clearInterval(progressTimer);

      if (result && result.code === 1 && result.data && result.data.resultImageUrl) {
        // 完成进度条
        this.setData({ aiProgress: 100 });

        // 延迟一下显示完成效果
        setTimeout(() => {
          // 换装成功，跳转到首页显示结果
          app.globalData.modelImage = result.data.resultImageUrl;

          // 隐藏AI处理动画
          this.setData({
            aiProcessing: false,
            aiProgress: 0
          });

          // 更新试穿状态
          this.updateProductState(item.productId, { tryOnLoading: false });

          wx.showToast({
            title: '试穿完成！',
            icon: 'success'
          });

          // 跳转到首页查看结果
          wx.switchTab({
            url: '/pages/index/index'
          });

          console.log('✅ 试穿成功，新图片:', result.data.resultImageUrl);
        }, 500);
      } else {
        throw new Error(result.msg || '换装失败');
      }
    } catch (error) {
      console.error('❌ 试穿失败:', error);

      // 清除进度条定时器
      clearInterval(progressTimer);

      // 隐藏AI处理动画
      this.setData({
        aiProcessing: false,
        aiProgress: 0
      });

      // 更新试穿状态
      this.updateProductState(item.productId, { tryOnLoading: false });

      wx.showToast({
        title: '试穿失败，请重试',
        icon: 'none'
      });
    }
  },

  // 调用AI换装API（复用首页的逻辑）
  callTryOnAPI(modelImage, clothingImage, token, clothesType = 'Upper-body') {
    const app = getApp();

    return new Promise((resolve, reject) => {
      console.log('🔄 调用AI换装API');
      console.log('模特图片:', modelImage);
      console.log('服装图片:', clothingImage);
      console.log('服装类型:', clothesType);
      console.log('API地址:', `${app.globalData.baseUrl}/ai/change-clothes`);

      wx.request({
        url: `${app.globalData.baseUrl}/ai/change-clothes`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        data: {
          modelImageUrl: modelImage,
          clothesImageUrl: clothingImage,
          clothesType: clothesType,
          logoAdd: 1
        },
        success: (res) => {
          console.log('📥 AI换装API响应:', res);
          resolve(res.data);
        },
        fail: (error) => {
          console.error('❌ AI换装API调用失败:', error);
          reject(new Error('网络请求失败: ' + error.errMsg));
        }
      });
    });
  },

  // 切换收藏状态
  async toggleFavorite(e) {
    const item = e.currentTarget.dataset.product;
    console.log('❤️ 切换收藏状态:', item);

    const app = getApp();
    const token = app.globalData.token;

    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    try {
      // 乐观更新UI
      const newFavoriteStatus = !item.isFavorited;
      this.updateProductState(item.productId, { 
        isFavorited: newFavoriteStatus,
        favoriteCount: (item.favoriteCount || 0) + (newFavoriteStatus ? 1 : -1)
      });

      // 调用API
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/products/${item.productId}/favorite`,
          method: newFavoriteStatus ? 'POST' : 'DELETE',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: resolve,
          fail: reject
        });
      });

      if (response.statusCode === 200 && response.data.code === 1) {
        wx.showToast({
          title: newFavoriteStatus ? '已收藏' : '已取消收藏',
          icon: 'success',
          duration: 1000
        });
      } else {
        // 如果API调用失败，回滚UI状态
        this.updateProductState(item.productId, { 
          isFavorited: !newFavoriteStatus,
          favoriteCount: (item.favoriteCount || 0) + (newFavoriteStatus ? -1 : 1)
        });
        throw new Error(response.data.msg || '操作失败');
      }
    } catch (error) {
      console.error('❌ 收藏操作失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 查看商品详情
  viewProductDetail(e) {
    const item = e.currentTarget.dataset.product;
    console.log('📱 查看商品详情:', item);

    // 这里可以跳转到商品详情页面
    wx.showToast({
      title: '商品详情功能开发中',
      icon: 'none'
    });
  }
})
